package com.qdsg.ysg.doctor.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.ainemo.sdk.otf.ConnectNemoCallback;
import com.ainemo.sdk.otf.LoginResponseData;
import com.ainemo.sdk.otf.NemoSDK;
import com.hjq.shape.view.ShapeTextView;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.base.BaseFragment;
import com.qdsg.ysg.doctor.eventbus.VersionUpdateEvent;
import com.qdsg.ysg.doctor.ui.HistoryListActivity;
import com.qdsg.ysg.doctor.ui.IMActivity;
import com.qdsg.ysg.doctor.ui.RefuseListActivity;
import com.qdsg.ysg.doctor.ui.TeamListActivity;
import com.qdsg.ysg.doctor.ui.activity.checkout.MedicalSkillsBillingActivity;
import com.qdsg.ysg.doctor.ui.dialog.GuideDialog;
import com.qdsg.ysg.doctor.ui.dialog.UpdateDialog;
import com.qdsg.ysg.doctor.ui.kotlin.CloudListActivity;
import com.qdsg.ysg.doctor.util.HarmonyUtil;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.UIConstants;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.DocInfoResponse;
import com.rest.response.DocStatusCountResponse;
import com.rest.response.MineResponse;
import com.rest.response.VersionResponse;

import org.greenrobot.eventbus.EventBus;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.PreferencesHelper;

/**
 * @author DELL
 */
public class HomeFragment extends BaseFragment {

    @BindView(R.id.iv_call)
    ImageView ivCall;
    @BindView(R.id.iv_news)
    ImageView ivNews;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_work_status)
    TextView tvWorkStatus;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.tv_access)
    TextView tvAccess;
    @BindView(R.id.tv_accept)
    TextView tvAccept;
    @BindView(R.id.tv_patient)
    TextView tvPatient;
    @BindView(R.id.btn_history)
    TextView btnHistory;
    @BindView(R.id.daijiezhen)
    ShapeTextView daijiezhen;
    @BindView(R.id.tv_unread_daijiezhen)
    ShapeTextView tvUnreadDaijiezhen;
    @BindView(R.id.tv_unread_jinxingzhong)
    ShapeTextView tvUnreadJinxingzhong;
    @BindView(R.id.btn_history_cloud)
    TextView btnHistoryCloud;
    @BindView(R.id.tv_unread_daizhenduan)
    ShapeTextView tvUnreadDaizhenduan;
    @BindView(R.id.quanbuyueyue)
    ShapeTextView quanbuyueyue;
    @BindView(R.id.tv_unread_quanbuyueyue)
    ShapeTextView tvUnreadQuanbuyueyue;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.chufangbohui)
    RelativeLayout chufangbohui;
    @BindView(R.id.btn_team_manage)
    TextView btnTeamManage;
    @BindView(R.id.tv_ask_ongoing)
    ShapeTextView tvAskOngoing;
    @BindView(R.id.tv_cloud_ongoing)
    ShapeTextView tvCloudOngoing;

    @SuppressLint("StaticFieldLeak")
    private static HomeFragment homeFragment;

    private String xyAccount;
    private String xyPassword;

    @Override
    protected int getLayoutResource() {
        return R.layout.fra_home;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        getDocInfo();
        getVersion();
        String token = PreferencesHelper.getInstance().getString(mContext, "token");
        xyAccount = PreferencesHelper.getInstance().getString(mContext, "xyAccount");
        xyPassword = PreferencesHelper.getInstance().getString(mContext, "xyPassword");
        if (!UtilString.isEmpty(token)) {
            xyLogin();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        getCountStatus();
        getMineInfo();
        tvName.setText(BaseApplication.name);
        tvDetail.setText(BaseApplication.jobTitle);

//        BaseApplication.avatar = "https://testeseal.certca.cn:8088/api/download/5B2BAD0818D0/a4dcbb94d28311edbf50005056813149/eyJhbGciOiJIUzM4NCJ9.eyJqdGkiOiI2Zjg2OWM4ZWJkNWYxMWVkYmY1MDAwNTA1NjgxMzE0OWE0ZGNiYjk0ZDI4MzExZWRiZjUwMDA1MDU2ODEzMTQ5IiwiaXNzIjoiempjYSIsInN1YiI6IjZmODY5YzhlYmQ1ZjExZWRiZjUwMDA1MDU2ODEzMTQ5YTRkY2JiOTRkMjgzMTFlZGJmNTAwMDUwNTY4MTMxNDkiLCJpYXQiOjE2ODA4NDkxMzUsImV4cCI6MTY4MDg0OTQzNX0.Cqu3LeF5aGucUdDisV1S-z0LNWHAnkDXroFbLOx9VqLzFyfNrJjgTjJbLPBeeuX5";

        if (!UtilString.isEmpty(BaseApplication.avatar)) {
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, BaseApplication.avatar, imgHead);
        } else {
            if ("女".equals(BaseApplication.sex)) {
                imgHead.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_girl));
            } else {
                imgHead.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_boy));
            }
        }
    }


    @OnClick({R.id.iv_call, R.id.iv_news, R.id.tv_accept, R.id.btn_history, R.id.daijiezhen, R.id.tv_ask_ongoing, R.id.btn_history_cloud, R.id.tv_cloud_ongoing, R.id.quanbuyueyue, R.id.chufangbohui, R.id.btn_team_manage, R.id.ll_team})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_call:
                break;
            case R.id.iv_news:
                break;
            case R.id.tv_accept:
                break;
            case R.id.btn_history: //图文历史问诊
                startActivity(HistoryListActivity.class);
                break;
            case R.id.daijiezhen: //图文待接诊
                Bundle bundle = new Bundle();
                bundle.putString(UIConstants.IM_FLAG, "0");
                startActivity(IMActivity.class, bundle);
                break;
            case R.id.tv_ask_ongoing://图文进行中
                Bundle bundleOne = new Bundle();
                bundleOne.putString(UIConstants.IM_FLAG, "1");
                startActivity(IMActivity.class, bundleOne);
                break;
            case R.id.btn_history_cloud://云门诊历史记录
                Bundle bundleHistory = new Bundle();
                bundleHistory.putString(UIConstants.FLAG, "304");
                startActivity(CloudListActivity.class, bundleHistory);
                break;
            case R.id.tv_cloud_ongoing://云门诊进行中
                Bundle bundleTwo = new Bundle();
                bundleTwo.putString(UIConstants.FLAG, "302");
                startActivity(CloudListActivity.class, bundleTwo);
                break;
            case R.id.quanbuyueyue:
                Bundle bundleAll = new Bundle();
                bundleAll.putString(UIConstants.FLAG, "300");
                startActivity(CloudListActivity.class, bundleAll);
                break;
            case R.id.chufangbohui:
                startActivity(RefuseListActivity.class);
                break;
            case R.id.btn_team_manage:
            case R.id.ll_team:
                startActivity(TeamListActivity.class);
                break;
            default:
                break;
        }
    }

    private void getDocInfo() {
        RestProxy.getInstance().getDocInfo(new Observer<DocInfoResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(DocInfoResponse docInfoResponse) {
                tvPatient.setText(docInfoResponse.data.allPatient);
                tvScore.setText(docInfoResponse.data.avgScore);
                tvAccess.setText(docInfoResponse.data.lastDayVisit);
                tvAccept.setText(docInfoResponse.data.lastDayReceive);

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getCountStatus() {
        RestProxy.getInstance().getDocCountStatus(new Observer<DocStatusCountResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(DocStatusCountResponse docStatusCountResponse) {
                if (docStatusCountResponse.data.notInquiry != 0) {
                    daijiezhen.setText("待接诊" + "(" + docStatusCountResponse.data.notInquiry + ")");
                } else {
                    daijiezhen.setText("待接诊");
                }

                if (docStatusCountResponse.data.inInquiry != 0) {
                    tvAskOngoing.setText("进行中" + "(" + docStatusCountResponse.data.inInquiry + ")");
                } else {
                    tvAskOngoing.setText("进行中");
                }

                if (docStatusCountResponse.data.clouddjz != 0) {
                    tvCloudOngoing.setText("进行中" + "(" + docStatusCountResponse.data.clouddjz + ")");
                } else {
                    tvCloudOngoing.setText("进行中");
                }
                if (docStatusCountResponse.data.cloudtotal != 0) {
                    quanbuyueyue.setText("全部预约" + "(" + docStatusCountResponse.data.cloudtotal + ")");
                } else {
                    quanbuyueyue.setText("全部预约");
                }
                tvNum.setText(docStatusCountResponse.data.rejectCount + "条");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getMineInfo() {
        RestProxy.getInstance().getMineInfo(new Observer<MineResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(MineResponse mineResponse) {
//                if (mineResponse.data.value == 1) {
//                    tv_work_status.setText("工作中");
//                } else {
//                    tv_work_status.setText("休息中");
//                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void getVersion() {
        RestProxy.getInstance().getVersion(new Observer<VersionResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(VersionResponse versionResponse) {
                PackageManager pm = mContext.getPackageManager();
                PackageInfo pi;
                String versionName = "";
                int versionCode = 0;
                try {
                    pi = pm.getPackageInfo(mContext.getPackageName(), 0);
                    versionCode = pi.versionCode;
                    versionName = pi.versionName;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                if (versionResponse.data.vision > versionCode && versionResponse.data.isUpdate == 1) {
                    if (HarmonyUtil.readPureModeState(mContext) == 1) {
                        showCodeDialog(versionResponse.data.url, versionResponse.data.isUpdate);
                    } else {
                        showPureModeDialog();
                    }
                }
                EventBus.getDefault().postSticky(new VersionUpdateEvent(versionResponse.data.url, versionName, versionResponse.data.vision > versionCode));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void showPureModeDialog() {
        GuideDialog guideDialog = GuideDialog.newInstance();
        guideDialog.setmListener(new GuideDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                startActivity(intent);
            }

            @Override
            public void onCancel() {

            }
        });
        guideDialog.show(getChildFragmentManager(), "guideDialog");
    }

    private void showCodeDialog(final String url, int isUpdate) {
        UpdateDialog mUpdateDialog = UpdateDialog.newInstance(isUpdate, false);
        mUpdateDialog.show(getChildFragmentManager(), "mUpdateDialog");
        mUpdateDialog.setmListener(new UpdateDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                Intent intent = new Intent();
                intent.setData(Uri.parse(url));//Url 就是你要打开的网址
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent); //启动浏览器
                Objects.requireNonNull(getActivity()).finish();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    //小鱼登录
    private void xyLogin() {
        NemoSDK.getInstance().loginXYlinkAccount(BaseApplication.xyAccount, BaseApplication.xyPassword, new ConnectNemoCallback() {

            @Override
            public void onFailed(String s) {
                BaseApplication.isXyLogin = false;
                LogUtil.e("小鱼登陆失败错误码：$errorCode" + s);
            }

            @Override
            public void onSuccess(LoginResponseData loginResponseData, boolean b) {
                BaseApplication.isXyLogin = true;
                LogUtil.e("小鱼登陆成功");
            }

            @Override
            public void onNetworkTopologyDetectionFinished(LoginResponseData loginResponseData) {

            }
        });
    }

    public static HomeFragment newInstance() {
        if (homeFragment == null) {
            homeFragment = new HomeFragment();
            return homeFragment;
        } else {
            return homeFragment;
        }
    }

    public static void Logout() {
        homeFragment = null;
    }

}
